package com.ying.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.ying.domain.po.Address;
import com.ying.domain.po.User;
import com.ying.domain.vo.AddressVO;
import com.ying.domain.vo.UserVO;
import com.ying.enums.UserStatus;
import com.ying.mapper.UserMapper;
import com.ying.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liujunjie
 * @Description description
 * @Date 2024-09-07 16:17
 **/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    @Transactional
    public void deductBalance(Long id, Integer money) {
        User user = getById(id);
        if (user == null || user.getStatus() == UserStatus.FROZEN) {
            throw new RuntimeException("用户状态异常！");
        }
        if (user.getBalance() < money) {
            throw new RuntimeException("用户余额不足！");
        }
        int remainBalance = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance, remainBalance)
                .set(remainBalance == 0, User::getStatus, UserStatus.FROZEN)
                .eq(User::getId, id)
                .eq(User::getBalance, user.getBalance())//乐观锁
                .update();
    }

    @Override
    public List<User> queryUsers(String name, Integer status, Integer minBalance, Integer maxBalance) {
        return lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance)
                .le(maxBalance != null, User::getBalance, maxBalance)
                .list();
    }

    @Override
    public UserVO queryUserAndAddressById(Long id) {
        User user = getById(id);
        if (user != null && user.getStatus() == UserStatus.FROZEN) {
            throw new RuntimeException("用户状态异常");
        }
        List<Address> addresses = Db.lambdaQuery(Address.class).eq(Address::getUserId, id).list();
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        if (CollectionUtil.isNotEmpty(addresses)) {
            userVO.setAddresses(BeanUtil.copyToList(addresses, AddressVO.class));
        }
        return userVO;
    }

    @Override
    public List<UserVO> queryUserAndAddressByIds(List<Long> ids) {
        // 查询用户
        List<User> users = listByIds(ids);
        if (CollUtil.isEmpty(users)) {
            return Collections.emptyList();
        }
        //查询地址
        // 获取用户id集合
        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
        // 根据用户id查询地址
        List<Address> addresses = Db.lambdaQuery(Address.class).
                in(Address::getUserId, userIds).
                list();
        //转换地址VO
        List<AddressVO> addressVOS = BeanUtil.copyToList(addresses, AddressVO.class);
        // 用户地址根据用户ID分组处理
        Map<Long, List<AddressVO>> addressVOSMap = new HashMap<>();
        if (CollUtil.isNotEmpty(addressVOS)) {
            addressVOSMap = addressVOS.stream().
                    collect(Collectors.groupingBy(AddressVO::getUserId));
        }
        List<UserVO> list = new ArrayList<>(users.size());
        for (User user : users) {
            //转换User的PO为VO
            UserVO vo = BeanUtil.copyProperties(user, UserVO.class);
            vo.setAddresses(addressVOSMap.get(user.getId()));
            //用户VO里面加入地址VO
            list.add(vo);
        }
        return list;
    }
}
